(function () {
    let pageid = 0,
        isOne = true;
    init()

    function init() {
        getData()
        $("button").click(clickButton)
        $("#select").click(clickSelect)
        changePrev()
    }

    function getData() {
        $.ajax({
            url: "http://chst.vip:1234/api/getmoneyctrl?",
            data: {
                pageid: pageid
            }
        }).then(res => {
            createGoodsList(res.result)
            $("#main .goodsList li").click(function () { //跳转详情页
                let productid = $(this).attr("productid");
                location.href = `../pages/moneyctrl_details.html?productid=${productid}`
            })
            if (isOne) { //只创建一次option 后面调用getData时候不执行下面代码
                createOption(res)
                isOne = false;
            }
        })
    }

    function createGoodsList(data) {
        let html = data.reduce((value, item) => {
            return value += `
                    <li productid=${item.productId}>
                        <div class="left">${item.productImgSm}</div>
                        <div class="right">
                        <h3>${item.productName}</h3>
                        <div class="other">
                            <span class="from">${item.productFrom}</span>
                            <span class="time">${item.productTime}</span>
                            <i>${item.productComCount}</i>
                        </div>
                        </div>
                    </li> 
                `
        }, '')
        $(".goodsList").html(html)
    }

    function createOption(data) { //创建下拉菜单
        let num = Math.ceil(data.totalCount / data.pagesize)
        let html = ""
        for (var i = 0; i < num; i++) { //option添加value 方便获取
            html += `
                <option value=${i}>
                    ${i+1}/${num}
                </option>
            `
        }
        $("#main select").html(html)
    }

    function clickButton(e) { //点击button切换页面
        if ($(this).attr("class") === "top") {
            pageid--;
            if (pageid < 0) {
                pageid = 0;
                return;
            }
        } else {
            pageid++;
            if (pageid > 14) {
                pageid = 14;
                return;
            }
        }
        changePrev()
        $("select").val(pageid)
        getData();
    }

    function clickSelect(e) { //点击select切换页面
        if ($(e.target).val() === pageid) return;
        pageid = $(e.target).val();
        changePrev()
        getData();
    }

    function changePrev() { //按钮置灰
        if (pageid == 0) $(".top").attr("disabled", true)
        else $(".top").attr("disabled", false);
        if (pageid == 14) $(".bottom").attr("disabled", true)
        else $(".bottom").attr("disabled", false);
    }
    $("footer>.nav li").eq(2).click(function () { //返回顶部动漫效果
        $("html").stop().animate({
            scrollTop: 0
        }, 200)
    })
}())